import React, { useEffect, useState } from 'react';
import styles from './index.less';
import { useDebounceFn, useSetState } from 'ahooks';
import * as echarts from 'echarts';
import { Form, DatePicker, Select, Button, message, Popconfirm, Divider } from 'antd';
import _ from 'lodash';
import moment from 'moment';
import { connect } from 'umi';

import { CaretLeftOutlined, CaretRightOutlined, UploadOutlined } from '#/utils/antdIcons.js';
import { HttpCode } from '#/utils/contacts.js';

import { SERVER_URL_OBJ } from '@/../config/urlConfig';
import { PageLoading, TRDefault, TRCheckboxModal, DimensionalSort } from '@/components/index.js';
import { export_json_to_excel } from '@/utils/fileExport.js';
import { useRem } from '@/hooks/index.js';

import { ChartDealTariff, ChartDealIncome } from '../Charts/index.js';
import { SELECT_DATA, OPTION_KEY, tableHead, operators, headerMap } from '../../helper';
import { formatJson, pointConvert } from '../../utils.js';
import { queryReanalyzeDataData } from '../../services.js';
import BaseTable from '../BaseTable';
import Step from '../Step';
import { TjStation } from '@/pages/ETrade/components';

const { RangePicker } = DatePicker;
const monthFormat = 'YYYYMMDD';
let dataInit: moment.Moment[] = [];
// // 当前日期大于当前月的2号
if (moment().diff(moment().startOf('month'), 'days') > 1) {
  dataInit = [moment().startOf('month'), moment()];
} else {
  dataInit = [
    moment().subtract(1, 'months').startOf('month'),
    moment().subtract(1, 'months').endOf('month'),
  ];
}

const MyStations = (props: any) => {
  const { value = [], onChange, options = [], treeData = [], optionAll = [], className } = props;
  const title = '交易单元';
  const isEmpty = !treeData.length;
  useEffect(() => {
    if (!value.length) {
      onChange(optionAll);
    }
  }, [optionAll]);
  const onHandleModal = async () => {
    if (isEmpty) return;
    const result = await TRCheckboxModal.show({
      title,
      value,
      treeData,
    });
    if (result?.index === 1 && result.checkedKeys.length) {
      onChange(result.checkedKeys);
    }
    TRCheckboxModal.dismiss();
  };
  const onDeselect = () => {
    if (value.length === 1) {
      onChange(optionAll);
    }
  };
  return (
    <div className={className}>
      <Select
        // value={value}
        value={
          !value.length
            ? '请选择交易单元'
            : value.length === optionAll.length
            ? '全部'
            : `${value.length}项/${optionAll.length}项`
        }
        style={{
          width: 200,
        }}
        options={options}
        maxTagCount={1}
        open={false}
        showSearch={false}
        showArrow={true}
        onClick={onHandleModal}
        onChange={onChange}
        onDeselect={onDeselect}
      />
    </div>
  );
};
const PowerForecastAdjusted = ({ menuCode, buttonPermissions, power = [] }: any) => {
  const [loading, setLoading] = useState(false),
    [listLoading, setListLoading] = useState(false),
    [tableDataSource, setTableDataSource] = useState([]), //主表格数据
    [tableHeader, setTableHeader]: any = useState(), //表头
    [stations, setStations] = useState<any>([]), // 全部场站（平铺）
    [stationTree, setStationTree] = useState<any>([]), // 已选省份的场站树
    [optionAll, setOptionAll] = useState<any>([]), //所选省份全部场站(全选)
    [param, setParam] = useState([SELECT_DATA[0], SELECT_DATA[1]]), //灵活聚合项
    [form] = Form.useForm(),
    reSize = useRem(1920),
    [echartsComparisonQuantityData, setEchartsComparisonQuantityData] = useState<any>({}), //阶段A模拟与阶段B量价对比
    [echartsComparisonIncomeData, setEchartsComparisonIncomeData] = useState<any>({}), //阶段A模拟与阶段B收入对比
    [echartsParam, setEchartsParam]: any = useState(), //图表筛选参数
    [filterUnitOptions, setFilterUnitOptions] = useState(), //父维度筛选 交易单元列表
    [dateTime, setDateTime] = useState<any>(), //父维度筛选 时间
    [regions, setRegions] = useState<any[]>([]), // 全部省份
    [isFullScreenEcharts, setIsFullScreenEcharts] = useState(false), // 是否为图表全屏展示
    [isFullScreenTable, setIsFullScreenTable] = useState(false), // 是否为表格全屏展示
    [visible, setVisible] = useState(false), // 控制大数据查询前提示
    [stepData, setStepData] = useState(6),
    [state, setState] = useSetState<any>({
      refData: [],
    });

  /** handle data */
  async function init() {
    // 获取数据权限
    // setLoading(true);
    // const res = await queryUnitOptions({menuCode}).catch(() => setLoading(false));
    // setLoading(false);
    // if (res?.statusCode === HttpCode.SUCCESS) {
    //
    // }
    initDataPower(power);
  }

  //获取省份对应交易单元
  const getStationOptions = (data: any) => {
    const _optionAll = _.flatten(data.map((i: any) => i.children?.map((y: any) => y.stationId)));
    form.setFieldsValue({
      unit: _optionAll,
    });
    setStationTree(data);
  };

  function initDataPower(data = [] as any) {
    // 处理数据权限
    if (!data) {
      // setErrorMsg('暂无数据权限');
      return;
    }
    // regions = [];
    const _stations = [] as any;
    data.map((x: any) => {
      // 公司
      (x?.children || []).map((y: any) => {
        // 省份
        (y?.children || []).map((z: any) => {
          // 场站
          _stations.push(z);
        });
      });
    });

    const stationsIds = _stations
      .filter((item: any) => item.marketId == data[0].marketId)
      ?.map((item: any) => item?.stationId || '');
    setRegions(data);
    setStations(_stations);
    getStationOptions(data?.[0]?.children);
    form.setFieldsValue({ region: data[0].marketId });
    const values = {
      date: dataInit,
      unit: stationsIds,
      step: stepData,
    };
    setEchartsParam({
      ...values,
      timeOrder: '24',
    });
    //重新渲染表格数据
    // eslint-disable-next-line @typescript-eslint/no-use-before-define
    _onFinish.run(values);
  }

  //切换省份
  const onRegionChange = (value: any, opt: any) => {
    form.setFieldsValue({
      unit: [],
    });
    getStationOptions(opt.children);
  };
  //取出非合计行默认第一行 最后一个子维度 作为echarts的横坐标
  const _getXAXIS = (data: any, arr: any[]) => {
    const _temp: any[] = [];
    const recursion = (item: any, index: number): any[] => {
      _temp.push({
        tag: item[0]?.tag,
        title: item[0]?.title,
      });
      if (item[0]?.children instanceof Array && item.length > 0) {
        return recursion(item[0].children, index - 1);
      }
      return _temp;
    };
    return recursion(data, arr.length - 1);
  };

  const getClassName = () => {
    let classNameEcharts = styles.charts;
    let classNameTable = styles.table;
    if (isFullScreenEcharts) {
      classNameEcharts = `${styles.chartsFullWidth}`;
      classNameTable = `${styles.tableNoWidth}`;
    } else if (isFullScreenTable) {
      classNameEcharts = `${styles.chartsNoWidth}`;
      classNameTable = `${styles.tableFullWidth}`;
    }

    return {
      classNameEcharts,
      classNameTable,
    };
  };

  const confirm = useDebounceFn(
    () => {
      setVisible(false);
      form && form.submit();
    },
    { wait: 500 },
  );

  const handleVisibleChange = () => {
    confirm.run();
  };
  /**建立echarts链接 */
  const getRef: any = (refData: any) => {
    const arr = [...state.refData];
    state.refData.push(refData);
    arr.push(refData);
    if (arr.length >= 2) {
      echarts.connect([...arr]);
    }
    setState({
      refData: arr,
    });
  };
  //根据父维度 筛选出图表所需数据  return:最后一个维度数组
  const _getFilterXAXIS = (data: any, arr: any[]): any[] => {
    const _echartsParam = _.cloneDeep(echartsParam);
    //取最后一个维度 第一行数据
    const recursion = (item: any, index: number): any[] => {
      const _item: any[] = [];
      item.forEach((t: any) => {
        if (t.title === '合计') return;
        _item.push(t);
      });
      let _temp: any[] = [];
      //如果已经是最后一个维度
      if (arr.length - 1 <= index) {
        return _item;
      }
      _item.forEach((t: any) => {
        t.title === _echartsParam[OPTION_KEY[arr[index]]] &&
          (_temp = recursion(t.children, index + 1));
      });
      return _temp;
    };
    return recursion(data, 0);
  };
  //获取默认第一行 根据传入维度递归获取数据
  const _getDimensionData = (data: any, deepIndex: number): any[] => {
    if (deepIndex) {
      return _getDimensionData(
        data[0].children.length ? data[0].children : data[1].children,
        deepIndex - 1,
      );
    }
    return data;
  };
  //dealFunc
  const dealFunc = (tag: string, meta: string[], title: any, value: any[]) => {
    let obj: any = {};
    obj = {
      title:
        tag === '时点' ? pointConvert(title) : tag === '日期' ? title.replaceAll('-', '') : title,
      tag: tag,
    };
    meta.forEach((_t: string, _i: number) => {
      obj[headerMap[_t]] = _t.includes('电量')
        ? parseFloat(value[_i]).toFixed(3)
        : parseFloat(value[_i]).toFixed(2);
    });
    return obj;
  };
  //totalDealFunc
  const totalDealFunc = (tag: string, meta: string[], title: any, value: any[]) => {
    let obj: any = {};
    obj = {
      title: title,
      tag: tag,
    };
    meta.forEach((_t: string, _i: number) => {
      obj[headerMap[_t]] = _t.includes('电量')
        ? parseFloat(value[_i]).toFixed(3)
        : parseFloat(value[_i]).toFixed(2);
    });
    obj.children = [];
    return obj;
  };
  //处理表格数据 dataSource表格数据 postdata选项
  const getNewDataSource = (dataSource: any, order: any) => {
    if (!dataSource) return [];
    const formatForTable = (item: any, optionName: any, index = 0) => {
      const arr: any[] = [];
      Object.entries(item).map((t: any) => {
        if (t[0] === 'total') {
          return;
        }
        //最后一个维度为数组
        if (t[1] instanceof Array) {
          arr.push(dealFunc(optionName[index], dataSource.meta, t[0], t[1]));
          return;
        }
        const obj = dealFunc(optionName[index], dataSource.meta, t[0], t[1].total);
        obj.children = formatForTable(t[1], optionName, index + 1);
        arr.push(obj);
      });
      arr.sort((a: any, b: any) => {
        if (optionName[index] === '交易单元') {
          return a.title.localeCompare(b.title, 'zh-CN');
        }
        //默认时点排序方式
        return a.title > b.title ? 1 : -1;
      });
      return arr;
    };
    // 添加合计行
    const result = [
      totalDealFunc(order[0], dataSource.meta, '合计', dataSource.data.total),
      ...formatForTable(dataSource.data, order),
    ];
    return result;
  };
  //请求表格数据
  async function _fetchFile(postdata: any) {
    setListLoading(true);
    setTableDataSource([]);
    const res = await queryReanalyzeDataData(postdata).catch(() => {});
    setListLoading(false);
    if (res.statusCode === HttpCode.SUCCESS) {
      const data: any = getNewDataSource(res.data, postdata.order);
      setTableDataSource(data);
      setTableHeader(tableHead);
      if (data.length) {
        const _data = _.cloneDeep(data);
        //设置图表数据
        const _echarsData = _getXAXIS(_data.splice(1), SELECT_DATA);
        //设置父维度列表值
        setFilterUnitOptions(
          (form.getFieldValue('unit')?.length ? form.getFieldValue('unit') : optionAll).map(
            (t: any) => {
              const item = stations.find((_t: any) => t == _t.stationId);
              return {
                label: item.stationName,
                value: item.stationName,
              };
            },
          ),
        );
        setDateTime(form.getFieldValue('date'));
        //设置父维度选择默认值【合约量价图】默认：第一个维度
        setEchartsParam({
          date:
            postdata.order.includes('日期') &&
            moment(_echarsData.find((t) => t.tag === '日期').title).format('YYYYMMDD'),
          unit:
            postdata.order.includes('交易单元') &&
            _echarsData.find((t) => t.tag === '交易单元').title + '',
          timeOrder: postdata.order.includes('时点') && '0100',
        });
      }
    }
  }

  const onexport = () => {
    if (!tableDataSource.length) return;
    const hasSave =
      buttonPermissions.filter((item: any) => item.menuCode === 'TransactionProcessContrastExport')
        .length > 0;
    if (!hasSave) {
      return message.info('请联系管理员获取相关权限');
    }
    const filename = `中长期复盘`;
    const params: any = {
      multiHeader: [],
      header: [param[0]],
      data: [],
      merges: ['B1:D1', 'E1:I1', 'J1:O1', 'P1:P2', 'Q1:S1', 'T1:V1', 'W1:Y1'],
      filename,
    };
    const data = tableDataSource;
    const dataFalt: any[] = [];
    data.map((x: any) => {
      dataFalt.push(x);
      (x?.children || []).map((y: any) => {
        dataFalt.push(y);
        (y?.children || []).map((z: any) => {
          dataFalt.push(z);
          (z?.children || []).map((e: any) => {
            dataFalt.push(e);
          });
        });
      });
    });
    const filterVal: string[] = ['title'];
    const multiHeader = ['聚合维度'];
    tableHeader?.forEach((item: any) => {
      //第一级
      multiHeader.push(params.multiHeader.includes(item.parentName) ? '' : item.parentName);
      //最后一级
      params.header.push(item.name);
      filterVal.push(item.field);
    });
    params.multiHeader = [multiHeader];
    params.data = formatJson(filterVal, dataFalt);
    export_json_to_excel(params);
  };
  //根据筛选参数 重绘图表
  const repaint = () => {
    const _echarsData = _getFilterXAXIS(tableDataSource, param);
    const _xaxis = _echarsData.map((t) => t.title);
    setEchartsComparisonQuantityData({
      XAXIS: _xaxis,
      simulationStrategyMediumAndLongTermElectricity: _echarsData.map(
        (t) => t.simulationStrategy_MediumAndLongTermElectricity,
      ),
      simulationStrategyTheBalanceCharge: _echarsData.map(
        (t) => t.simulationStrategy_TheBalanceCharge,
      ),
      simulationStrategyIntegratedAverage: _echarsData.map(
        (t) => t.simulationStrategy_IntegratedAverage,
      ),
      mediumAndLongAccumulatedMediumAndLongTermElectricity: _echarsData.map(
        (t) => t.mediumAndLong_AccumulatedMediumAndLongTermElectricity,
      ),
      mediumAndLongAccumulatedMediumAndLongTermPrice: _echarsData.map(
        (t) => t.mediumAndLong_AccumulatedMediumAndLongTermPrice,
      ),
    });
    setEchartsComparisonIncomeData({
      XAXIS: _xaxis,
      simulationAndMediumToLongTermComparisonIncomeDeviation: _echarsData.map(
        (t) => t.simulationAndMediumToLongTermComparison_IncomeDeviation,
      ),
      simulationAndMediumToLongTermComparisonRecyclingDeviation: _echarsData.map(
        (t) => t.simulationAndMediumToLongTermComparison_RecyclingDeviation,
      ),
      simulationAndMediumToLongTermComparisonTotalDeductionIncomeDeviation: _echarsData.map(
        (t) => t.simulationAndMediumToLongTermComparison_TotalDeductionIncomeDeviation,
      ),
    });
  };

  const _onFinish = useDebounceFn(
    (values: any) => {
      // 查询
      const _formData: any = values,
        _date = _formData.date,
        _startDate = _date && moment(_date[0]).format('YYYY-MM-DD'),
        _endDate = _date && moment(_date[1]).format('YYYY-MM-DD'),
        _step = _formData.step,
        _unit = _formData.unit;
      // _param = [SELECT_DATA[0], SELECT_DATA[1]];
      // setParam(_param); //初始化聚合维度
      _fetchFile({
        cacheable: true,
        needTotal: true,
        operators: operators,
        order: param,
        param: JSON.stringify({
          stationIdList: _unit,
          startDate: _startDate,
          endDate: _endDate,
          tag: _step,
        }),
        url: `${
          // @ts-ignore
          SERVER_URL_OBJ[`${CLIENT_ENV === 'dev' ? 'test' : CLIENT_ENV}` || 'release']
        }/reanalyze/LongTermPointReplayUpgrade/getTransactionProcessContrast`,
      });
    },
    { wait: 500 },
  );
  const _renderHeader = () => {
    const initialValues = () => {
      return {
        date: dataInit,
        step: stepData,
      };
    };
    return (
      <div className={styles.header}>
        <Form
          form={form}
          initialValues={initialValues()}
          className={styles.formStyles}
          onFinish={_onFinish.run}
        >
          <Form.Item name="region" className={styles.cell_item}>
            <Select
              options={regions}
              style={{ width: 200 }}
              placeholder="请选择省份"
              showSearch={true}
              onChange={onRegionChange}
            />
          </Form.Item>
          <Form.Item name="unit" className={styles.cell_item}>
            <TjStation options={stationTree} />
            {/*<MyStations options={stations} treeData={stationTree} optionAll={optionAll} />*/}
          </Form.Item>
          <Form.Item
            name="date"
            className={styles.cell_item}
            rules={[{ required: true, message: '请选择日期' }]}
          >
            <RangePicker className={styles.select_date} format={'YYYYMMDD'} separator={'-'} />
          </Form.Item>
          <Form.Item name="step" className={styles.cell_item}>
            <Step
              onChange={(e: any) => {
                form.setFieldsValue({ step: e });
                setStepData(e);
              }}
              step={stepData}
            />
          </Form.Item>
          <Popconfirm
            title="您选择的数据量较大，可能延长加载时间或引起页面崩溃，是否确认查询？"
            visible={visible}
            onVisibleChange={handleVisibleChange}
            onConfirm={() => confirm.run()}
            onCancel={() => setVisible(false)}
            okText="确认"
            cancelText="取消"
          >
            <Button className={styles.submit} type="primary" htmlType="submit">
              查询
            </Button>
          </Popconfirm>
          <Button
            className={styles.submit}
            onClick={() => {
              setStepData(6);
              form.setFieldsValue({
                region: regions[0].value,
                unit: optionAll,
                date: dataInit,
                step: 6,
              });
              onRegionChange(regions[0].value);
              form.submit();
            }}
            ghost
          >
            重置
          </Button>
          <div
            className={`${styles.import} ${!tableDataSource.length && styles.disabled}`}
            onClick={onexport}
          >
            <UploadOutlined style={{ fontSize: '0.12rem' }} />
            导出
          </div>
        </Form>
      </div>
    );
  };
  //表格图表内容区域渲染
  const _renderContent = () => {
    if (listLoading)
      return (
        <div className={styles.emty}>
          <PageLoading />
        </div>
      );
    if (!tableDataSource.length) return <TRDefault type={'empty'} />;
    /*获取设置选择器下拉列表项*/
    const pointOptions =
      param.includes('时点') && param.indexOf('时点') < param.length - 1
        ? _getDimensionData(tableDataSource, param.indexOf('时点')).map((t) => ({
            label: t.title,
            value: t.title,
          }))
        : [];
    //重新聚合
    const _polymerize = (options: any) => {
      setParam(options);
      //重新渲染表格数据
      const _formData: any = form.getFieldsValue(true),
        _date = _formData.date,
        _startDate = _date && moment(_date[0]).format('YYYY-MM-DD'),
        _endDate = _date && moment(_date[1]).format('YYYY-MM-DD'),
        _step = _formData.step,
        _unit = _formData.unit;
      _fetchFile({
        cacheable: true,
        needTotal: true,
        operators: operators,
        order: options,
        param: JSON.stringify({
          stationIdList: _unit,
          startDate: _startDate,
          endDate: _endDate,
          tag: _step,
        }),
        url: `${
          // @ts-ignore
          SERVER_URL_OBJ[`${CLIENT_ENV === 'dev' ? 'test' : CLIENT_ENV}` || 'release']
        }/reanalyze/LongTermPointReplayUpgrade/getTransactionProcessContrast`,
      });
    };
    const _selectUnitOnChange = (value: any) => {
      setEchartsParam({
        ...echartsParam,
        unit: value,
      });
    };
    const _selectDateOnChange = (value: any) => {
      setEchartsParam({
        ...echartsParam,
        date: value.format('YYYYMMDD'),
      });
    };
    const _selectPointOnChange = (value: any) => {
      setEchartsParam({
        ...echartsParam,
        timeOrder: value,
      });
    };
    //控制日历可选范围
    const disabledDate = (current: any) => {
      const _date = dateTime;
      return (current && current < _date[0].startOf('day')) || current > _date[1].endOf('day');
    };
    return (
      <>
        <div className={[styles.leftBox, getClassName().classNameTable].join(' ')}>
          <div
            className={styles.leftArrow}
            onClick={() => {
              setIsFullScreenTable(!isFullScreenTable);
            }}
          >
            {isFullScreenTable ? <CaretLeftOutlined /> : <CaretRightOutlined />}
          </div>
          <DimensionalSort
            reSize={reSize}
            optionsArray={SELECT_DATA}
            option={param}
            onClick={_polymerize}
          />
          <BaseTable tableData={tableDataSource} tableHeader={tableHeader} text={param[0]} />
        </div>
        {!isFullScreenEcharts ? (
          <Divider type="vertical" style={{ height: '100%', margin: '.15rem 0 0' }} />
        ) : null}
        <div className={[styles.rightBox, getClassName().classNameEcharts].join(' ')}>
          <div className={styles.filter_group}>
            <div className={styles.flex}>
              {param.map((t: any, i: number) => {
                if (t === '交易单元' && param[param.length - 1] !== '交易单元') {
                  {
                    return (
                      <Select
                        key={i}
                        className={styles.filter_unit}
                        style={{ marginLeft: i === 0 ? 0 : '.16rem' }}
                        showSearch
                        placeholder="选择交易单元"
                        onChange={_selectUnitOnChange}
                        value={echartsParam.unit}
                        options={filterUnitOptions}
                        filterOption={(input, option) => {
                          return (option?.label as unknown as string)
                            .toLowerCase()
                            .includes(input.toLowerCase());
                        }}
                      />
                    );
                  }
                }
                if (t === '日期' && param[param.length - 1] !== '日期') {
                  {
                    return (
                      <DatePicker
                        key={i}
                        onChange={_selectDateOnChange}
                        inputReadOnly
                        allowClear={false}
                        className={styles.filter_date}
                        style={{ marginLeft: i === 0 ? 0 : '.16rem' }}
                        value={moment(echartsParam.date)}
                        format={monthFormat}
                        disabledDate={disabledDate}
                      />
                    );
                  }
                }
                if (t === '时点' && param[param.length - 1] !== '时点') {
                  {
                    return (
                      <Select
                        key={i}
                        className={styles.filter_point}
                        style={{ marginLeft: i === 0 ? 0 : '.16rem' }}
                        placeholder="选择时点"
                        onChange={_selectPointOnChange}
                        value={echartsParam.timeOrder}
                        options={pointOptions.filter((item) => item.label !== '合计')}
                      />
                    );
                  }
                }
              })}
            </div>
          </div>
          <div className={styles.content_box}>
            <div
              className={styles.rightArrow}
              onClick={() => {
                setIsFullScreenEcharts(!isFullScreenEcharts);
              }}
            >
              {isFullScreenEcharts ? <CaretRightOutlined /> : <CaretLeftOutlined />}
            </div>
            {!echartsComparisonQuantityData?.XAXIS?.length ? (
              <TRDefault type={'emptysm'} />
            ) : (
              <>
                <div className={styles.title} style={{ paddingTop: 0 }}>
                  阶段A模拟与阶段B量价对比
                </div>
                <div style={{ flex: 1 }}>
                  <ChartDealTariff
                    data={echartsComparisonQuantityData}
                    scale={reSize / 100}
                    getRef={getRef}
                  />
                </div>
                <div className={styles.title}>阶段B实际收入-阶段A模拟收入</div>
                <div style={{ flex: 1 }}>
                  <ChartDealIncome
                    data={echartsComparisonIncomeData}
                    scale={reSize / 100}
                    getRef={getRef}
                  />
                </div>
              </>
            )}
          </div>
        </div>
      </>
    );
  };
  useEffect(() => {
    if (power && power?.length !== 0) {
      init();
    }
  }, [power]);

  useEffect(() => {
    if (tableDataSource.length > 0) {
      repaint();
    }
  }, [echartsParam]);

  if (loading) return <PageLoading />;
  return (
    <>
      {_renderHeader()}
      <div className={styles.content_body}>
        <div className={styles.content}> {_renderContent()}</div>
      </div>
    </>
  );
};
export default connect(({ global }: any) => ({
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
}))(PowerForecastAdjusted);
